/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.example.fuel.rxutil;

import ohos.eventhandler.EventHandler;
import ohos.eventhandler.InnerEvent;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import io.reactivex.Scheduler;
import io.reactivex.disposables.Disposable;
import io.reactivex.disposables.Disposables;
import io.reactivex.exceptions.UndeliverableException;
import io.reactivex.functions.Consumer;
import io.reactivex.plugins.RxJavaPlugins;

/**
 * @since 2021-06-08
 */
final class HandlerScheduler extends Scheduler {
    private final EventHandler handler;
    private final boolean async;

    HandlerScheduler(EventHandler handler, boolean async) {
        this.handler = handler;
        this.async = async;
    }

    /**
     * scheduleDirect
     *
     * @param runnable runnable
     * @param delay delay
     * @param unit unit
     * @return Disposable
     */
    @Override
    public Disposable scheduleDirect(Runnable runnable, long delay, TimeUnit unit) {
        Runnable run = runnable;
        if (run == null) {
            throw new NullPointerException("run == null");
        }
        if (unit == null) {
            throw new NullPointerException("unit == null");
        }
        run = RxJavaPlugins.onSchedule(run);
        ScheduledRunnable scheduled = new ScheduledRunnable(handler, run);
        handler.postTask(scheduled, unit.toMillis(delay));
        return scheduled;
    }

    @Override
    public Worker createWorker() {
        return new HandlerWorker(handler, async);
    }

    private static final class HandlerWorker extends Worker {
        private final EventHandler handler;
        private final boolean async;

        private volatile boolean disposed;

        HandlerWorker(EventHandler handler, boolean async) {
            this.handler = handler;
            this.async = async;
        }

        /**
         * schedule
         *
         * @param runnable runnable
         * @param delay delay
         * @param unit unit
         * @return Disposable
         */
        @Override
        public Disposable schedule(Runnable runnable, long delay, TimeUnit unit) {
            Runnable run = runnable;
            if (run == null) {
                throw new NullPointerException("run == null");
            }
            if (unit == null) {
                throw new NullPointerException("unit == null");
            }
            if (disposed) {
                return Disposables.disposed();
            }

            run = RxJavaPlugins.onSchedule(run);
            ScheduledRunnable scheduled = new ScheduledRunnable(handler, run);
            InnerEvent message = InnerEvent.get(scheduled);
            message.object = this;
            handler.sendEvent(message, unit.toMillis(delay));
            handler.sendSyncEvent(null);

            // Re-check disposed state for removing in case we were racing a call to dispose().
            if (disposed) {
                handler.removeTask(scheduled);
                return Disposables.disposed();
            }

            return scheduled;
        }

        @Override
        public void dispose() {
            disposed = true;
            handler.removeAllEvent();
        }

        @Override
        public boolean isDisposed() {
            return disposed;
        }
    }

    private static final class ScheduledRunnable implements Runnable, Disposable {
        private final EventHandler handler;
        private final Runnable delegate;

        private volatile boolean disposed; // Tracked solely for isDisposed().

        ScheduledRunnable(EventHandler handler, Runnable delegate) {
            this.handler = handler;
            this.delegate = delegate;
        }

        @Override
        public void run() {
            delegate.run();
        }

        @Override
        public void dispose() {
            handler.removeAllEvent();
            disposed = true;
        }

        @Override
        public boolean isDisposed() {
            return disposed;
        }
    }

    /**
     * setRxJavaErrorHandler
     */
    public static void setRxJavaErrorHandler() {
        RxJavaPlugins.setErrorHandler(new Consumer<Throwable>() {
            @Override
            public void accept(Throwable temp) {
                Throwable throwableT = temp;
                if (throwableT instanceof UndeliverableException) {
                    return;
                } else if ((throwableT instanceof IOException)) {
                    // fine, irrelevant network problem or API that throws on cancellation
                    return;
                } else if (throwableT instanceof InterruptedException) {
                    // fine, some blocking code was interrupted by a dispose call
                    return;
                } else if ((throwableT instanceof NullPointerException)
                    || (throwableT instanceof IllegalArgumentException)) {
                    // that's likely a bug in the application
                    Thread.currentThread().getUncaughtExceptionHandler()
                        .uncaughtException(Thread.currentThread(), throwableT);
                    return;
                } else if (throwableT instanceof IllegalStateException) {
                    // that's a bug in RxJava or in a custom operator
                    Thread.currentThread().getUncaughtExceptionHandler()
                        .uncaughtException(Thread.currentThread(), throwableT);
                    return;
                } else {
                    return;
                }
            }
        });
    }

}
